import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

//年月日时分秒
String formatter_1 = "yyyy.MM.dd HH:mm:ss";
//年月日时分
String formatter_2 = "yyyy.MM.dd HH:mm";

// 11:40
TimeOfDay? stringToTimeOfDay(String? time) {
  if (ObjectUtil.isEmptyString(time)) return null;

  List<String> timeList = time!.split(":");
  if (ObjectUtil.isEmptyList(timeList)) return null;
  if (timeList.length != 2) return null;

  TimeOfDay? timeOfDay;
  try {
    int hour = int.parse(timeList[0]);
    int minute = int.parse(timeList[1]);
    timeOfDay = TimeOfDay(hour: hour, minute: minute);
  } catch (e) {
    timeOfDay = null;
  }

  return timeOfDay;
}

String TimeOfDayToString(TimeOfDay dateTime) {
  String timeStr = "";
  if (dateTime.hour < 10) {
    timeStr += "0${dateTime.hour}";
  } else {
    timeStr += dateTime.hour.toString();
  }
  timeStr += ":";
  if (dateTime.minute < 10) {
    timeStr += "0${dateTime.minute}";
  } else {
    timeStr += dateTime.minute.toString();
  }

  return timeStr;
}

//2020.10.25 10:10:01
DateTime? stringToDateTime(String? time) {
  if (ObjectUtil.isEmptyString(time)) return null;

  String formattedString = time!.replaceAll(".", "-");
  DateTime? dateTime;

  try {
    dateTime = DateTime.parse(formattedString);
  } catch (e) {
    dateTime = null;
  }
  return dateTime;
}

String DateTimeToString({String? timeFormatter, DateTime? dateTime}) {
  String formattedString = timeFormatter ?? formatter_1;
  var dateFormatter = DateFormat(formattedString);
  return dateFormatter.format(dateTime!);
}
